home *** CD-ROM | disk | FTP | other *** search
- Path: dispatch.news.demon.net!demon!sianotts.demon.co.uk
- From: John Rawson <JR@sianotts.demon.co.uk>
- Newsgroups: comp.lang.c++
- Subject: 3d Array allocation
- Date: Thu, 11 Apr 1996 18:37:36 +0100
- Organization: None
- Message-ID: <316D4360.6446@sianotts.demon.co.uk>
- NNTP-Posting-Host: sianotts.demon.co.uk
- X-NNTP-Posting-Host: sianotts.demon.co.uk
- X-Mailer: Mozilla 2.0 (Win16; I)
- MIME-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
-
- Hello group.
-
- I'm very new to c++ and have just wrote a function to allocate a 3d array
- of char's it compiles and seems to work OK,I'm just worried that if the
- memory allocation fails then I'm deleting everything correctly ready to
- try again.All criticisms/improvements would be appreciated.Many thanks.
-
- here's the function...
-
- char ***New_3D_Char_Array(int n1,int n2,int n3)
- {
- int i,j,k;
- char ***Array_Pointer=new char **[n1];
- if (!Array_Pointer)
- return NULL;//serious lack of memory!!!
- for (i=0;i<n1;i++)
- {
- Array_Pointer[i]=new char *[n2];
- if (!Array_Pointer[i])//check for allocation failure
- {
- //delete what we've allocated up to yet
- for (k=0;k<i;k++)
- delete[] Array_Pointer[k];
- delete [] Array_Pointer;
- return NULL;
- }
- }
- for (i=0;i<n1;i++)
- for (j=0;j<n2;j++)
- {
- Array_Pointer[i][j]=new char[n3];
- if (!Array_Pointer[i][j])//check again for failure
- {
- //again,delete what's already gone
- //first what we've done in the current j loop
- for (k=0;k<j;k++)
- delete [] Array_Pointer[i][k];
- //and then then the other i & j loops
- for (k=0;k<i;k++)
- {
- for (j=0;j<n2;j++)
- delete[] Array_Pointer[k][j];
- delete [] Array_Pointer[k];
- }
- delete [] Array_Pointer;
- return NULL;
- }
- }
- return Array_Pointer;
- }
-